package com.mokylin.dbschema.util;

import com.mokylin.dbschema.pojo.DbVersion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.Objects;
import java.util.StringJoiner;

/**
 * @author 李朝(Li.Zhao)
 * @since 2015/8/31.
 */

public class GlobalUtils {

    private final static Logger LOG = LoggerFactory.getLogger(GlobalUtils.class);

    private static String serverIdentify;

    /**
     * 升级前的版本信息
     */
    private static DbVersion originalDbVersion;

    public static DbVersion getOriginalDbVersion() {
        if(originalDbVersion==null)return null;
        DbVersion tmp = new DbVersion();
        copyProperties(originalDbVersion,tmp);
        return tmp;
    }

    public static void setOriginalDbVersion(DbVersion originalDbVersion) {
        if(originalDbVersion==null)return;
        GlobalUtils.originalDbVersion = new DbVersion();
        copyProperties(originalDbVersion,GlobalUtils.originalDbVersion);
    }

    public static String getServerIdentify() {
        if(StringUtils.isNotBlank(serverIdentify)){
            return serverIdentify;
        }
        try {
            byte[] hardwareAddress = new byte[0];
            try {
                hardwareAddress = NetworkInterface.getByInetAddress(InetAddress.getLocalHost()).getHardwareAddress();
            } catch (SocketException | UnknownHostException e) {
                return InetAddress.getLocalHost().getHostName();
            }
            if (hardwareAddress == null || hardwareAddress.length <= 0) {
                return "";
            }
            StringJoiner joiner = new StringJoiner("-");
            for (byte b : hardwareAddress) {
                int v = b & 0xFF;
                String hv = Integer.toHexString(v);
                if (hv.length() < 2) {
                    hv = 0 + hv;
                }
                joiner.add(hv);
            }
            return serverIdentify=joiner.toString();
        } catch (Exception e) {
            LOG.warn("can not get server mac:{}",e.getMessage());
        }
        return "";
    }

    public static final String TMPDIR = System.getProperty("java.io.tmpdir");



    private static void copyProperties(DbVersion source, DbVersion dest) {
        Objects.requireNonNull(source);
        Objects.requireNonNull(dest);
        dest.setId(source.getId());
        dest.setDesc(source.getDesc());
        dest.setVersion(source.getVersion());
        dest.setUpdateTime(source.getUpdateTime());
        dest.setStatus(source.getStatus());
        dest.setBuildingServerMac(source.getBuildingServerMac());
    }
}